import pygame
import time
from playsound import playsound
import sounddevice as sd
import soundfile as sf
import simpleaudio as sa
import vlc
import wave
import numpy as np

def test_pygame():
    print("\n=== Testing pygame ===")
    try:
        pygame.init()
        
        pygame.mixer.init()
        pygame.mixer.music.load('response.mp3')
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            time.sleep(0.1)
        pygame.mixer.quit()
        print("pygame playback completed")
    except Exception as e:
        print(f"pygame error: {e}")

def test_playsound():
    print("\n=== Testing playsound ===")
    try:
        playsound('response.mp3')
        print("playsound playback completed")
    except Exception as e:
        print(f"playsound error: {e}")

def test_sounddevice():
    print("\n=== Testing sounddevice ===")
    try:
        data, samplerate = sf.read('response.mp3')
        sd.play(data, samplerate)
        sd.wait()
        print("sounddevice playback completed")
    except Exception as e:
        print(f"sounddevice error: {e}")

def test_simpleaudio():
    print("\n=== Testing simpleaudio ===")
    try:
        # SimpleAudio doesn't support MP3 directly, we need to convert the audio first
        data, samplerate = sf.read('response.mp3')
        # Convert to 16-bit PCM
        audio_data = (data * 32767).astype(np.int16)
        play_obj = sa.play_buffer(audio_data, 2 if len(audio_data.shape) > 1 else 1, 2, samplerate)
        play_obj.wait_done()
        print("simpleaudio playback completed")
    except Exception as e:
        print(f"simpleaudio error: {e}")

def test_vlc():
    print("\n=== Testing VLC ===")
    try:
        player = vlc.MediaPlayer('response.mp3')
        player.play()
        time.sleep(1)  # Give time for the media to load
        duration = player.get_length() / 1000  # Convert to seconds
        time.sleep(duration)
        player.stop()
        print("vlc playback completed")
    except Exception as e:
        print(f"vlc error: {e}")

if __name__ == "__main__":
    print("Testing different audio libraries for playing response.mp3")
    print("Please listen carefully to the quality of each playback")
    
    input("Press Enter to start pygame test...")
    test_pygame()
    
    input("Press Enter to start playsound test...")
    test_playsound()
    
    input("Press Enter to start sounddevice test...")
    test_sounddevice()
    
    input("Press Enter to start simpleaudio test...")
    test_simpleaudio()
    
    input("Press Enter to start vlc test...")
    test_vlc()
    
    print("\nAll tests completed!")
